//
//  LXREmoticonController.swift
//  表情键盘
//
//  Created by MACBOOK on 16/10/15.
//  Copyright © 2016年 刘袭锐. All rights reserved.
//

import UIKit
/// cell标识
fileprivate let EmoticonCell = "EmoticonCell"
/// 每行表情个数
fileprivate let LineEmoticonCount : CGFloat = 7

class LXREmoticonController: UIViewController {

    
    //FIXME: 懒加载控件
    /// collectionView
    fileprivate lazy var collectionView : UICollectionView = UICollectionView(frame: CGRect.zero, collectionViewLayout: EmoticonCollectionViewLayout())
    /// toolBar
    fileprivate lazy var toolBar : UIToolbar = UIToolbar()
    
    //FIXME: 定义属性
    /// 数据数组
    fileprivate lazy var manager = EmoticonManager()
    fileprivate var emoticonCallBack:(_ emoticon : Emoticon)->()
    
    //FIXME: 重写构造函数
    init(emoticonCallBack : @escaping (_ emoticon : Emoticon)->()){
        // 闭包赋值
        self.emoticonCallBack = emoticonCallBack
        // 必须重写的父类构造方法
        super.init(nibName: nil, bundle: nil)
    }
    
    required init?(coder aDecoder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }

    //FIXME: 系统回调
    override func viewDidLoad() {
        super.viewDidLoad()
        
        setupUI()
        prepareForCollectionView()
        prepareForToolBar()

    }
}

// MARK:- 设置UI界面
extension LXREmoticonController{
    
    //FIXME: 设置控件
    fileprivate func setupUI(){
        //1.添加控件
        view.addSubview(collectionView)
        view.addSubview(toolBar)
        
        //2.设置Frame (用系统VFL)
        //2.1 关闭系统自动调整
        collectionView.translatesAutoresizingMaskIntoConstraints = false
        toolBar.translatesAutoresizingMaskIntoConstraints = false
    
        //2.2 创建视图字典
        let views = ["tBar" : toolBar,"cView" : collectionView] as [String : Any]
        
        //2.3定义约束容器
        let tBarH = "H:|-0-[tBar]-0-|"//水平约束
        let cViewV = "V:|-0-[cView]-0-[tBar]-0-|"//垂直约束
        var cons = NSLayoutConstraint.constraints(withVisualFormat: tBarH, options: [], metrics: nil, views: views)
        cons += NSLayoutConstraint.constraints(withVisualFormat: cViewV, options: [.alignAllLeft,.alignAllRight], metrics: nil, views: views)
        //2.4添加约束到View
        view.addConstraints(cons)

        //3.设置属性
        collectionView.backgroundColor = UIColor.purple
        toolBar.backgroundColor = UIColor.lightGray
        
    }
    
    //FIXME: 准备加载collectionView
    fileprivate func prepareForCollectionView() {
        //1.注册cell
        collectionView.register(LXREmoticonCell.self, forCellWithReuseIdentifier: EmoticonCell)
        //2.设置数据源和代理
        collectionView.dataSource = self
        collectionView.delegate = self
    }
    
    //FIXME: 准备ToolBar
    fileprivate func prepareForToolBar(){
        //1.定义toolBar中得titles
        let titles = ["最近","默认","emoji","浪小花"]
        //2.遍历标题,创建item
        var index = 0
        var tempItems = [UIBarButtonItem]()
        for title in titles{
            let item = UIBarButtonItem(title: title, style: .plain, target: self, action: #selector(LXREmoticonController.toolBarItemClick(item:)))
            item.tag = index
            index += 1
            tempItems.append(item)
            if title == titles.last {
                continue
            }
            //添加弹簧
            tempItems.append(UIBarButtonItem(barButtonSystemItem: .flexibleSpace, target: nil, action: nil))
            
        }
        //3.赋值给toolBar数组
        toolBar.items = tempItems
        toolBar.tintColor = UIColor.orange
    }
}

// MARK:- 事件监听
extension LXREmoticonController{
    //FIXME: 点击工具栏Item
    @objc fileprivate func toolBarItemClick(item : UIBarButtonItem){
        //1.获取点击的item的tag
        let tag = item.tag
        //2.根据tag获取当前组
        let indexPath = IndexPath(item: 0, section: tag)
        //3.滚动到对应的位置
        collectionView.scrollToItem(at: indexPath, at: .left, animated: true)
    }
}

// MARK:- 数据源,代理
extension LXREmoticonController : UICollectionViewDataSource,UICollectionViewDelegate{
    //FIXME: 数据源
    func numberOfSections(in collectionView: UICollectionView) -> Int {
        return manager.packages.count
    }
    
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        // 取出表情包
        let package = manager.packages[section]
        return package.emoticons.count
    }
    
    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        // 1.创建cell
        let cell = collectionView.dequeueReusableCell(withReuseIdentifier: EmoticonCell, for: indexPath) as! LXREmoticonCell
        
        // 2.给cell设置数据
        
        let package = manager.packages[indexPath.section]
        let emoticon = package.emoticons[indexPath.item]
        cell.emoticon = emoticon
        
        return cell
    }
    //FIXME: 代理
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        //1.取出点击的表情
        let package = manager.packages[indexPath.section]
        let emotion = package.emoticons[indexPath.item]
        
        //2.将点击的表情插入最近的分组中
        insertRecentlyEmotion(emotion: emotion)
        
        //3.把emotion传到外部控制器
        emoticonCallBack(emotion)
        
    }
    //FIXME: 插入表情方法
    fileprivate func insertRecentlyEmotion(emotion : Emoticon){
        //1.如果是空白表情或者删除按钮,不需要插入
        if emotion.isRemove || emotion.isEmpty{
            return
        }
        //2.判断删除是否已有表情
        if (manager.packages.first!.emoticons.contains(emotion)){//如果包含此表情
            let index = (manager.packages.first?.emoticons.index(of: emotion))!
            manager.packages.first?.emoticons.remove(at: index)
        }else{//原来没有这个表情
            manager.packages.first?.emoticons.remove(at: 19) //删除按钮前一个空白按钮
        }

        //3.将emotion插入最近分组中
        manager.packages.first?.emoticons.insert(emotion, at: 0)
        
    }
}

// MARK:- 自定义流水布局
class EmoticonCollectionViewLayout: UICollectionViewFlowLayout {
    //FIXME: 重写布局初始化
    override func prepare() {
        super.prepare()
        
        // 计算大小,间距
        // itemWH大小
        let itemWH = UIScreen.main.bounds.width / LineEmoticonCount
        itemSize = CGSize(width: itemWH, height: itemWH)
        // item间距,通过内边距使每个item没有间距
        let margin : CGFloat = (collectionView!.bounds.height - 3 * itemWH) / 2
        collectionView?.contentInset = UIEdgeInsets(top: margin, left: 0, bottom: margin, right: 0)
        
        // 设置layout属性
        minimumLineSpacing = 0
        minimumInteritemSpacing = 0
        
        // 滚动方向(水平)
        scrollDirection = .horizontal
        
        //设置collectionView属性
        collectionView?.isPagingEnabled = true
        collectionView?.showsVerticalScrollIndicator = false
        collectionView?.showsHorizontalScrollIndicator = false
        
        
    }
    
}

